<template>
    <div id="rent" @click="show.keywordList=false">
        <div id="searchBar" ref="searchBar" class="searchBar">
            <div>
                <input type="text" v-model="selected.keywords" @click.stop @focus="show.keywordList=true" placeholder="输入区域/小区名"/>
                <ul v-if="show.keywordList">
                    <li v-for="item in selected.keywordList" :key="item" @click="selected.keywords=item">{{item}}</li>
                    <li>
                        <h1>搜索热词</h1>
                        <div>
                            <span v-for="hotWord in hotWords" :key="hotWord.message" @click="selected.keywords=hotWord.message">{{hotWord.message}}</span>
                        </div>
                    </li>
                </ul>
            </div>
            <button value="马上找房" @click="selectedJson.keywords=selected.keywords">马上找房</button>
        </div>
        <div id="homeContainer">
            <div id="tabs">
                <span><label>类型</label><a v-for="types in typeList" :key="types" :class="(selected.type===types)?'active':''"  @click="typechange(types)" href="#">{{types}} </a>
                <input type="search" ref="areaTypeInput"  v-model="nearbyLocation" placeholder="搜索附近房源" />
                </span>
                <hr />
                <span><label>区域</label><a v-for="area in areaList" :key="area" :class="(selected.area===area)?'active':''"  @click="areachange(area)" >{{area}} </a> </span>
                <span><label>价格</label><a v-for="price in priceList" :key="price" :class="(selected.price===price)?'active':''"  @click="pricechange(price)" >{{price}} </a> </span>
                <span><label>房型</label><a v-for="roomType in roomTypeList" :key="roomType" :class="(selected.roomType===roomType)?'active':''"  @click="roomTypechange(roomType)">{{roomType}} </a> </span>
                <span><label>面积</label><a v-for="size in sizeList" :key="size" :class="(selected.size===size)?'active':''"  @click="sizechange(size)">{{size}} </a> </span>
            </div>
            <div id="order">
                <span>
                    <label>排序</label><a v-for="order in orderList" :key="order" :class="(selected.order===order)?'orderActive':''"  @click="orderchange(order)">{{order}} </a>
                    <p>共为你找到{{rentMsgCount}}条记录</p>
                </span>
            </div>
            <div id="houseMsg" v-for="item in houseMsg" :key="item.id">
                <img :alt="item.name"  referrer="no-referrer" :src="item.thumb">
                <span id="Msg" >
                    <h1><a :href="item.pc_url" target="_blank">{{item.name}}</a><a @click="openFind(item)">请求合租</a></h1>
                    <p>{{item.house_type}} | {{item.size}}㎡ | {{item.height}}|  朝向&nbsp;{{item.toward}}</p>
                    <p>发布时间：{{item.edittime}}</p>
                    <p>地址：{{item.location}} </p>
                    <p style="color: #ff0a60;">{{item.away?'距离搜索源附近'+item.away+'米':''}}</p>
                    <div>{{item.price}}元/月</div>
                </span>
            </div>
            <div id="back-to-up" ref="btu">
                <a  href="#" class="el-icon-arrow-up" ></a>
            </div>
        </div>
        <findFriend id="findFriend2" :houseMsg="sendToFind" v-if="show.findFriend2" @close="closeFind()"></findFriend>
    </div>
</template>

<script>
    import findFriend from '../components/findFriend.vue';
    export default {
        name: "rent",
        data(){
            return{
                api:this.Global.api,
                qqLoginStatus:false,
                show:{
                    keywordList:false,
                    findFriend2:false
                },

                Autocomplete: null,

                typeList:['位置','公司','高校'],
                areaList:["不限","天河区","越秀区","海珠区","番禺区","花都区","白云区","黄埔区","萝岗区"],
                priceList:['不限','1000以下','1000-2000','2000-3000','3000-4000','4000以上'],
                roomTypeList:['不限','1室','2室','3室','4室及以上'],
                sizeList:['不限','50㎡以下','50㎡-70㎡','70㎡-90㎡','90㎡-120㎡','120㎡以上'],
                orderList:['默认','租金▼','面积▼','时间▼'],
                nearbyLocation:'',

                hotWords:[],
                houseMsg:[],
                rentMsg:[],
                rentMsgCount:0,
                selected:{
                    type:'位置',
                    area:'不限',
                    price:'不限',
                    roomType:'不限',
                    size:'不限',
                    order:"默认",
                    keywordList:[],
                    keywords:'',
                    lnglat:[]
                },

                sendToFind:{},

                selectedJson:{nextpage:'',house_type :0,price:0 ,size:0,height:'',location:'',house_list:'',keywords:'',lon:'',lat:''}
            }
        },
        props:['nowArea'],
        components:{
            findFriend
        },
        methods:{
            typechange(input){
                if(!input) return false;
                if(input !== this.selected.type)
                {
                    this.selected.type = input;
                    switch (input) {
                        case '位置': this.Autocomplete.setType('');break;
                        case '高校': this.Autocomplete.setType('141201');break;
                        case '公司': this.Autocomplete.setType('170000');break;
                    }
                }
            },
            areachange(input){
                if(!input) return false;
                if(input !== this.selected.area)
                {
                    this.selected.area = input;
                    this.selectedJson.nextpage = 0;
                }
                this.selectedJson.nextpage = 0;
                this.selectedJson.location = (this.selected.area !== '不限' ? this.selected.area.slice(0, 2) : '');
            },
            pricechange(input){
                if(!input) return false;
                if(input !== this.selected.price)
                {
                    this.selected.price = input;
                    this.selectedJson.nextpage = 0;
                    this.selectedJson.price = (this.selected.price !== '不限' ? this.priceList.indexOf(this.selected.price) : '');
                }
            },
            roomTypechange(input){
                if(!input) return false;
                if(input !== this.selected.roomType)
                {
                    this.selected.roomType = input;
                    this.selectedJson.nextpage = 0;
                    this.selectedJson.house_type = (this.selected.roomType !== '不限' ? this.roomTypeList.indexOf(this.selected.roomType) : '');
                }
            },
            sizechange(input){
                if(!input) return false;
                if(input !== this.selected.size)
                {
                    this.selected.size = input;
                    this.selectedJson.nextpage = 0;
                    this.selectedJson.size = (this.selected.size !== '不限' ? this.sizeList.indexOf(this.selected.size) : '');
                }
            },
            orderchange(input){
                if(!input) return false;
                if(input !== this.selected.order)
                {
                    this.selected.order = input;
                }
                else{
                    let cur = this.orderList.indexOf(input);
                    let order = this.orderList[cur];
                    if(order[2] === '▼') this.orderList[cur]=order.replace(/▼/g,'▲');
                    else this.orderList[cur]=order.replace(/▲/g,'▼');
                    this.selected.order = this.orderList[cur];
                }
                this.selectedJson.nextpage = 0;
                switch (this.selected.order) {
                    case '租金▼':
                        this.selectedJson.house_list = 2;
                        break;
                    case '租金▲':
                        this.selectedJson.house_list = 1;
                        break;
                    case '面积▼':
                        this.selectedJson.house_list = 4;
                        break;
                    case '面积▲':
                        this.selectedJson.house_list = 3;
                        break;
                    case '时间▼':
                        this.selectedJson.house_list = 5;
                        break;
                    case '时间▲':
                        this.selectedJson.house_list = 6;
                        break;
                    default: this.selectedJson.house_list = '';
                }
            },
            submitMsg(data) {
                return new Promise((resolve,reject)=>{
                    this.$axios.get(this.api+ '/index.php/index/housedata',{
                        params: data
                    }).then(res => {
                        if(res.status>=200&&res.status<300){
                            resolve(res);
                        } else {
                            reject(res.status);
                        }
                    })
                        .catch(error => {
                            alert(error);
                        });
                })
            },
            QQLoginCallBack(){
                let url = window.location.href;
                let Reg = /\?code=/i;
                if(Reg.test(url)){
                    let code = url.slice(url.search(Reg)+6,url.length);
                    if( document.cookie.indexOf('login_state=true')=== -1){
                        this.$axios.get(this.api+ '/index.php/index/qc_data',{params:{code: code}}).then(
                            res =>{
                                if(res.status>=200&&res.status<300){
                                    if(res.data.res===0){
                                        document.cookie = 'login_state=true';
                                        document.cookie = 'login_token=' + res.data.token;
                                        setTimeout(()=>{
                                            this.$emit('qqLoginState');
                                        },500)
                                    }else{
                                        alert('通过qq登录失败');
                                    }
                                } else {
                                    // console.log('登录失败',res.data);
                                }
                            }
                        )
                    }
                }
            },
            getHotWords(){
                this.$axios.post('http://129.204.175.168:8080/hotWords').then(res=>{
                    if(res.status>=200&&res.status<300){
                        this.hotWords = res.data.data;
                    }
                })
            },
            openFind(item){
                if(document.cookie.indexOf('login_state=true') === -1)
                {
                    alert('请先登录！')
                }else{
                    this.sendToFind=item;
                    this.show.findFriend2 = true;
                }
            },
            closeFind(){
                this.sendToFind=null;
                this.show.findFriend2=false;
            }
        },
        computed:{
          /*监听搜索框变化*/
          isKeywords(){
              return this.selected.keywords;
          }
        },
        watch: {
            nowArea() {
                this.selected.area = this.nowArea;
                this.selectedJson.location = (this.selected.area !== '不限' ? this.selected.area.slice(0, 2) : '');
            },
            selectedJson: {
                deep: true,
                handler() {
                    this.submitMsg(this.selectedJson).then(res => {
                        this.rentMsgCount = res.data.num;
                        if(this.rentMsgCount === 0) {
                            this.houseMsg = [];
                            alert('无结果')
                        }else if(this.selectedJson.nextpage===0){
                            this.rentMsg = res.data.data;
                            this.houseMsg = this.rentMsg.slice(0,10);
                        }else{
                            this.rentMsg.concat(res.data.data);
                        }
                        this.$forceUpdate();
                    }, err => {
                        alert(err)
                    });
                }
            },
            isKeywords(newValue,oldValue) {
                if(newValue!==oldValue)
                {
                    this.$axios.get('http://129.204.175.168:8080/autocomplete',{params:{prefix:this.selected.keywords}}).then(res=>{
                        if(res.status>=200&&res.status<300)
                        {
                            this.selected.keywordList = res.data.data;
                        }
                    })
                }
            },
            nearbyLocation(){
                if(this.nearbyLocation)
                {
                    let geocoder = new AMap.Geocoder({
                        city: "广州", //城市设为北京，默认：“全国”
                    });
                    geocoder.getLocation(this.nearbyLocation,(status,res)=>{
                        if(status === 'complete'){
                            this.selectedJson.lon=res.geocodes[0].location.lng;
                            this.selectedJson.lat=res.geocodes[0].location.lat;
                        }
                    })
                }else{
                    this.selectedJson.lon='';
                    this.selectedJson.lat='';
                }

            }
        },
        created() {
            this.getHotWords();
            this.QQLoginCallBack();
            this.selectedJson.nextpage = 0;
        },
        mounted(){
            this.Autocomplete= new AMap.Autocomplete({
                city:'广州市',
                input: this.$refs.areaTypeInput,
            });
            this.Autocomplete.on('select',res=>{
                this.nearbyLocation=res.poi.name;
            });
            window.onscroll=()=> {
                let scrollTop = document.documentElement.scrollTop || document.body.scrollTop ;
                let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                let offsetHeight = document.documentElement.offsetHeight || document.body.offsetHeight;
                let searchView = this.$refs.searchBar;
                let btu = this.$refs.btu;
                btu.style.top = (scrollTop+clientHeight*2/3)+'px';
                if (scrollTop > 120) {
                    searchView.classList.add("searchBarCopy");
                    btu.style.display = 'block';
                } else {
                    searchView.classList.remove("searchBarCopy");
                    btu.style.display = 'none';
                }
                if (this.houseMsg.length < this.rentMsgCount-1) {
                    if(this.houseMsg.length%500===0){
                        this.selectedJson.nextpage++;
                    }
                    if(scrollTop >= (offsetHeight-clientHeight-100))
                    this.houseMsg.push(this.rentMsg[this.houseMsg.length+1]);
                }
            }
        },
        destroyed(){
            window.onscroll = null;
        }
    }
</script>

<style scoped>
    #rent{
        min-width: 1000px;
        height: 100%;
    }
    #findFriend2{
        position: fixed;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
        z-index: 3;
        top: 0;
        overflow: auto;
        background-color: rgba(0,0,0,0.5);
    }
    #rent .searchBar{
        position: relative;
        z-index: 2;
        height: 50px;
        background-color: white;
        display: flex;
        justify-content: center;
        width: 100%;
        min-width: 1000px;
        background-color: rgba(255,255,255,0.8);
    }
    #rent .searchBar input{
        height: 35px;
        width: 600px;
        border:1px solid rgba(0,0,0,0.1);
        text-indent: 2em;
    }
    #rent .searchBar ul{
        width: 599px;
        top: 42.5px;
        background-color: white;
        border-right:1px solid rgba(0,0,0,0.1);
        border-left:1px solid rgba(0,0,0,0.1);
    }
    #rent .searchBar li{
        min-height: 30px;
        text-indent: 2em;
        line-height: 30px;
        border-bottom: 1px solid rgba(0,0,0,0.1);
        cursor: default;
    }
    #rent .searchBar li:hover{
        color: #ff0a60;
    }
    #rent .searchBar li h1{
        font-size: 0.8em;
        color: rgba(0,0,0,0.8);
    }
    #rent .searchBar li>div{
        margin: 0 2em;
        text-indent:0;
        font-size: 0.9em;
    }
    #rent .searchBar li:last-child:hover{
        color: #515151 ;
    }
    #rent .searchBar li>div>span{
        padding-right: 2em;
        cursor: pointer;
    }
    #rent .searchBar li>div>span:hover{
        color: #ff0a60;
    }
    #rent .searchBar button{
        width: 100px;
        position: relative;
        right: 2px;
        height: 37px;
        background-color: #ff0a60;
        border: 1px solid #ff0a60;
        color: white;
        font-size: 18px;
        border-radius: 0 3px 3px 0;
    }
    #rent .searchBar button:hover{
        filter: opacity(90%);
        cursor: pointer;
    }

    .searchBarCopy{
        z-index: 2;
        position: fixed !important;
        width: 100%;
        top: 0;
        height: 400px;
    }

    .searchBarCopy input,.searchBarCopy button{
        margin-top: 7.5px;
    }

    #homeContainer{
        /*居中显示*/
        width: 100%;
        height: 100%;
        position: relative;
        float: left;
        margin: 0 auto;
    }
    #tabs,#houseMsg,#order{
        background-color: white;
        position: relative;
        width: 60%;
        min-width: 900px;
        margin: 10px auto;
        font-size: 0.95em;
    }
    #tabs span,#order span{
        display: flex;
        align-items: center;
        width: auto;
        height: 15px;
        padding: 15px;
    }
    #homeContainer span a,#homeContainer label{
        color: black;
        margin: 5px;
        text-align: center;
        padding: 1px 6px 1px 6px;
        border-radius: 3px;
    }
    #homeContainer span label{margin-right:15px; }
    #homeContainer span a{
        color: rgba(0,0,0,0.8);
        text-decoration: none;
    }
    #tabs span a:hover, #tabs span .active{
        background-color: #ff0a60;
        color: white;
    }
    #tabs span input{
        margin-left: 10px;
        height: 27px;
        width: 200px;
        border:1px solid rgba(0,0,0,0.1);
        font-size: 0.9em;
        text-indent: 0.5em;
    }
    #tabs hr{
        border: 1px dashed rgba(0,0,0,0.1);
        width: 95%;
        margin: 0 auto;
    }
    #homeContainer a:hover{
        color: #ff0a60;
        text-decoration: none;
    }
    #homeContainer a{
        -webkit-transition: 0.3s cubic-bezier(0.5, -0.5, 0.25, 1.5);
        -moz-transition: 0.3s cubic-bezier(0.5, -0.5, 0.25, 1.5);
        -ms-transition: 0.3s cubic-bezier(0.5, -0.5, 0.25, 1.5);
        -o-transition: 0.3s cubic-bezier(0.5, -0.5, 0.25, 1.5);
        transition: 0.3s cubic-bezier(0.5, -0.5, 0.25, 1.5);
    }
    #homeContainer .orderActive{
        color: #ff0a60;
    }
    #homeContainer #order p{
        position: relative;
        color: rgba(0,0,0,0.7);
        left: 50%;
    }
    #Msg{
        display: inline-block;
             height: 150px;
             width: 70%;
             margin-top: 20px;
            margin-bottom: 20px;
         }
    #Msg h1{
        display: flex;
        align-items: center;
        justify-content: flex-start;
        height: 30px;
        font-size: 1.7em;
        padding-left:0 ;
        font-weight: normal;
        margin-bottom: 20px;
        /*border: 1px solid #ff0a60;*/
    }
    #Msg h1 a:nth-child(2){
        margin: 0;
        font-size: 13px;
        color: #ff0a60;
        border: 1px solid #ff0a60;
        border-radius: 5px;
    }
    #Msg p{
        font-size: small;
        padding-left: 10px;
        margin-top: 10px;
        color: rgba(0,0,0,0.5);
    }
    #Msg div{
        position: absolute;
        font-size: xx-large;
        left: 80%;
        top: 35%;
        color: #ff0a60;
    }
    #houseMsg img{
        float: left;
        height: 150px;
        width: 20%;
        margin: 20px;
    }
    #back-to-up{
        display: none ;
        width: calc(50% - 450px);
        position: absolute;
        right: 0;
    }
    #back-to-up>a{
        display: block !important;
        margin: 0 auto;
        width: 70px;
        height: 70px;
        background: white;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 10px;
        border: 2px solid #d8d8d8 !important;
        text-align: center;
        line-height: 70px;
        font-size: 3em;
    }
</style>